/*
 * Copyright (C) 2016 Lokiy(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  　　　　http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

@file:Suppress("PackageDirectoryMismatch")

package androidx.lifecycle

import java.io.Closeable

/**
 * ViewModels
 * @author Lokiy
 * 2021-04-26 10:41
 */
private const val KEY_LOADING = "ViewModel.isLoading"
private const val KEY_TOAST = "ViewModel.toast"


/**
 * 加载状态
 */
val ViewModel.isLoading: MutableLiveData<Boolean>
    get() {
        val loading: MutableLiveData<Boolean>? = this.getTag(KEY_LOADING)
        if (loading != null) {
            return loading
        }

//        return setTagIfAbsent(KEY_LOADING, CloseableObservableBoolean())
        return setTagIfAbsent(KEY_LOADING, NotifyWhenChangedValueLiveData())
    }


/**
 * toastLiveData
 */
val ViewModel.toastLiveData: MutableLiveData<String>
    get() {
        val toast: MutableLiveData<String>? = this.getTag(KEY_TOAST)
        if (toast != null) {
            return toast
        }
        return setTagIfAbsent(KEY_TOAST, MutableLiveData())
    }

/**
 * observe toast liveData
 */
fun ViewModel.observeToast(lifecycle: LifecycleOwner, observe: (String) -> Unit) {
    toastLiveData.observe(lifecycle, Observer {
        observe.invoke(it)
    })
}

/**
 * 值有变化的时候才会通知
 */
class NotifyWhenChangedValueLiveData<T> : MediatorLiveData<T>(), Closeable {

    override fun setValue(value: T?) {
        if (this.value != value) {
            super.setValue(value)
        }
    }

    override fun postValue(value: T?) {
        if (this.value != value) {
            super.postValue(value)
        }
    }

    override fun close() {
    }

    override fun toString(): String {
        return value.toString()
    }
}